<template>
  <div class="file-upload-component">
    <el-dialog 
      :title="title" 
      :visible.sync="dialogVisible" 
      :width="width" 
      @close="handleDialogClose"
      @open="handleDialogOpen"
    >
      <div class="upload-container">
        <el-upload class="upload-demo" drag action="http://125.39.77.18:9021/mall-admin/fileUpload/upload" :file-list="fileList" :on-success="handleUploadSuccess"
        	:on-error="handleUploadError" :on-remove="handleFileRemove" :before-upload="beforeUpload" multiple>
        	<i class="el-icon-upload"></i>
        	<div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      <!--  <span slot="footer" class="dialog-footer">
        	<el-button @click="dialogVisible = false">取 消</el-button>
        	<el-button type="primary" @click="save">确 定</el-button>
        </span> -->
			
        <!-- 文件列表 -->
        <div v-if="fileList.length > 0" class="file-list-section">
          <h4 class="section-title">文件列表</h4>
          <el-table :data="fileList" border size="mini" style="margin-top: 10px;">
            <el-table-column align="center" label="序号" type="index" width="60">
            </el-table-column>
            <el-table-column align="center" label="文件名称" prop="name" min-width="200">
              <template slot-scope="scope">
                <span :title="scope.row.name">{{ scope.row.name }}</span>
                <span v-if="scope.row.size" style="color: #999; font-size: 12px;">
                  ({{ formatFileSize(scope.row.size) }})
                </span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="文件类型" width="100">
              <template slot-scope="scope">
                <span>{{ getFileType(scope.row.name) }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)" size="mini">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" width="120">
              <template slot-scope="scope">
                <el-button 
                  type="text" 
                  size="mini" 
                  @click="gotoChanek(scope.row.response.data.url)"
                >预览</el-button>
                <el-button 
                  type="text" 
                  size="mini" 
                  style="color: #f56c6c;" 
                  @click="handleDelete(scope.$index)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm" :loading="confirmLoading">
          确定
        </el-button>
      </div>
    </el-dialog>
		
		<el-dialog title="图形资料文件" :visible.sync="isChakan" width="30%" :before-close="handleClose">
			<el-image :src="mapfile"></el-image>
			<span slot="footer" class="dialog-footer">
				<el-button @click="isChakan = false">取 消</el-button>
				<el-button type="primary" @click="isChakan = false">确 定</el-button>
			</span>
		</el-dialog>
  </div>
</template>

<script>
export default {
  name: 'FileUpload',
  
  props: {
    // 弹窗标题
    title: {
      type: String,
      default: '上传文件'
    },
    // 弹窗宽度
    width: {
      type: String,
      default: '800px'
    },
    // 外部控制弹窗显示
    visible: {
      type: Boolean,
      default: false
    },
		// 外部图片内容
		ImgUpload:{
			type: Array,
			default: false
		}
  },

  data() {
    return {
      dialogVisible: false,
      fileList: [],
      confirmLoading: false,
			currentFileSrc:[],
			mapfile:'',
			isChakan:false
    };
  },

  watch: {
    visible: {
      handler(newVal) {
        this.dialogVisible = newVal;
				this.fileList = this.ImgUpload
				console.log('999',this.ImgUpload )
      },
    },
    dialogVisible(newVal) {
      this.$emit('update:visible', newVal);
    }
  },

  methods: {
		gotoChanek(url){
			this.mapfile = url
			this.isChakan = true
		},
		// 格式化文件大小
		formatFileSize(bytes) {
		  if (bytes === 0) return '0 B';
		  const k = 1024;
		  const sizes = ['B', 'KB', 'MB', 'GB'];
		  const i = Math.floor(Math.log(bytes) / Math.log(k));
		  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
		},
		// 获取文件类型
		getFileType(fileName) {
		  const ext = fileName.split('.').pop().toLowerCase();
		  switch (ext) {
		    case 'pdf':
		      return 'PDF';
		    case 'doc':
		    case 'docx':
		      return 'Word';
		    case 'xls':
		    case 'xlsx':
		      return 'Excel';
		    case 'jpg':
		    case 'jpeg':
		    case 'png':
		    case 'gif':
		      return '图片';
		    default:
		      return '其他';
		  }
		},
    // 获取状态类型
    getStatusType(status) {
      switch (status) {
        case 'success':
          return 'success';
        case 'error':
          return 'danger';
        case 'uploading':
          return 'warning';
        default:
          return 'info';
      }
    },
    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 'success':
          return '成功';
        case 'error':
          return '失败';
        case 'uploading':
          return '上传中';
        default:
          return '待上传';
      }
    },
    // 弹窗打开
    handleDialogOpen() {
      this.$emit('open');
    },
    // 弹窗关闭
    handleDialogClose() {
      this.fileList = [];
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles();
      }
      this.$emit('close');
    },
		// 上传前验证
		beforeUpload(file) {
			const isExcel = file.type === 'application/vnd.ms-excel' ||
				file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
			// if (!isExcel) {
			//     this.$message.error('只能上传 Excel 文件！');
			//     return false;
			// }
		
			const isLt2M = file.size / 1024 / 1024 < 2;
			if (!isLt2M) {
				this.$message.error('上传文件大小不能超过 2MB!');
				return false;
			}
		
			return true;
		},
		// 文件选择变化
		handleFileRemove(file, fileList) {
			this.fileList = fileList;
			let arr = [...this.currentFileSrc];
			let i;
			arr.forEach((item, index) => {
				if (item.fileSize == file.size && item.name == file.name) {
					i = index
				}
			})
			arr.splice(i, 1);
			this.currentFileSrc = arr;
			console.log(this.currentFileSrc)
		
		},
		// 上传成功
		handleUploadSuccess(response, file, fileList) {
			this.fileList = fileList
			if (response.code == 200) {
				this.$message.success('文件上传成功');
				this.currentFileSrc.push(response.data)
			
				this.mapfile = response.data.url
				
			} else {
				this.$message.error('文件上传失败');
				let arr = [...fileList.map(i => i)]
				arr.pop();
				this.fileList = arr;
		
			}
		},
		// 删除文件
		handleDelete(index) {
		  this.$confirm('确认删除该文件？', '删除提示', {
		    confirmButtonText: '确定',
		    cancelButtonText: '取消',
		    type: 'warning'
		  }).then(() => {
		    this.fileList.splice(index, 1);
		    this.$message.success('删除成功');
		    this.$emit('delete', index);
		  }).catch(() => {
		    this.$message.info('已取消删除');
		  });
		},
		// 上传失败
		handleUploadError(err, file) {
			this.$message.error('文件上传失败');
		},
		
		// 取消
		handleCancel() {
		  this.dialogVisible = false;
		},
		// 确认
		handleConfirm() {
		  this.$emit('confirm', this.fileList);
		},
		
		handleClose(done) {
			this.$confirm('确认关闭？')
				.then(_ => {
					done();
					this.reter()
				})
				.catch(_ => {});
		},
  }
};
</script>

<style scoped>
/* 上传容器样式 */
.upload-container {
  padding: 20px 0;
  width: 100%;
}

.upload-dragger {
  width: 100% !important;
}

.upload-dragger .el-upload {
  width: 100% !important;
}

.upload-dragger .el-upload-dragger {
  width: 100% !important;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.2s ease;
  background-color: #fafafa;
  box-sizing: border-box;
}

.upload-dragger .el-upload-dragger:hover {
  border-color: #409EFF;
  width: 100%;
}

.upload-dragger .el-upload-dragger .el-icon-upload {
  font-size: 67px;
  color: #C0C4CC;
  margin: 40px 0 16px;
  line-height: 50px;
  width: 100%;
}

.upload-dragger .el-upload__text {
  color: #606266;
  font-size: 14px;
  text-align: center;
}

.upload-dragger .el-upload__text em {
  color: #409EFF;
  font-style: normal;
}

/* 模板下载样式 */
.template-download {
  margin-top: 15px;
  font-size: 14px;
  color: #606266;
}

.template-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.template-label {
  color: #606266;
  font-size: 14px;
}

.template-button {
  color: #409EFF;
  padding: 0;
  font-size: 14px;
  text-decoration: none;
}

.template-button:hover {
  color: #66b1ff;
}

/* 文件列表区域样式 */
.file-list-section {
  margin-top: 20px;
}

.section-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 500;
  color: #409eff;
  border-left: 4px solid #409eff;
  padding-left: 10px;
}

.dialog-footer {
  text-align: center;
  padding-top: 20px;
}

/* 全局样式覆盖 */
::v-deep .el-upload {
  width: 100% !important;
}

::v-deep .el-upload-dragger {
  width: 100% !important;
}
</style>